<template>
  <el-dialog v-model="show" title="权限分配" width="30%" align-center>
    <el-tree
      ref="treeRef"
      :data="treeData"
      show-checkbox
      node-key="id"
      :props="defaultProps"
    />
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="show = false">取消</el-button>
        <el-button type="primary" @click="allotJurisdiction"> 确定 </el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { useVModels } from '@vueuse/core'
import useVisible from '@/hooks/useVisible'

import { isEmpty } from 'lodash-es'

import {
  getAllTree,
  getTreeDetail,
  updataRoleJurisdiction,
  getRoleDetail,
  Tree,
} from '@/api/user/roleList'
import { ElTree } from 'element-plus'
import { CodeEnum } from '@/constants/http-code'

const defaultProps = {
  children: 'children',
  label: 'title',
}

const treeData = ref<Tree[]>([])

const emit = defineEmits(['update:show', 'refreshTable'])
const props = defineProps({
  /**
   * 是否显示弹窗
   */
  show: {
    type: Boolean,
    default: false,
  },
  roleId: {
    type: Number,
    default: 0,
  },
})
const { show } = useVModels(props)
const { roleId } = toRefs(props)

const treeRef = ref<InstanceType<typeof ElTree>>()

/**
 * 权限分配
 */
const allotJurisdiction = async () => {
  // 获取当前角色权限
  const res = await getRoleDetail(roleId.value)
  //获取选中节点
  const check = treeRef.value?.getCheckedKeys() as number[]
  //获取半选中节点
  const halfCheck = treeRef.value?.getHalfCheckedKeys() as number[]
  // 现将三个数据组合,然后通过filter进行筛选
  const arr = res.data.concat([...check, ...halfCheck]).filter((v, i, arr) => {
    return arr.indexOf(v) === arr.lastIndexOf(v)
  })
  // 定义添加的数组和删除的数组
  const add: number[] = []
  const del: number[] = []
  // 对筛选后的数组进行遍历,判断与原数组的不同,从而获取到该数据是添加的还是删除的
  arr.forEach((v) => {
    if (res.data.indexOf(v) === -1) {
      add.push(v)
    } else {
      del.push(v)
    }
  })
  console.log(`添加: ${add}`)
  console.log(`删除: ${del}`)
  // 发起请求更新数据
  const res1 = await updataRoleJurisdiction({
    roleId: roleId.value,
    add,
    del,
  })
  console.log(res1, 'res1')
  if ((res1.data = CodeEnum.UPDATE)) {
    show.value = false
  }
}

// 获取初始化树结构
const initTreeData = async () => {
  const res = await getAllTree()
  treeData.value = res.data
  setCheckedKeys()
}
initTreeData()
// 获取角色权限
const setCheckedKeys = async () => {
  const res = await getTreeDetail(roleId.value)
  treeRef.value?.setCheckedKeys(res.data)
}
</script>
<style lang="scss" scoped></style>
